package com.web.kdl.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.simp.config.ChannelRegistration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.messaging.simp.stomp.StompCommand;
import org.springframework.messaging.simp.stomp.StompHeaderAccessor;
import org.springframework.messaging.support.ChannelInterceptor;
import org.springframework.messaging.support.MessageHeaderAccessor;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketTransportRegistration;

import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {

    private static final Logger logger = LoggerFactory.getLogger(WebSocketConfig.class);
    private static final int MESSAGE_SIZE_LIMIT = 10 * 64 * 1024;

    // 添加连接计数器
    private final AtomicInteger connectionCount = new AtomicInteger(0);
    // 在 WebSocketConfig 类中添加会话跟踪
    private final Set<String> activeSessions = ConcurrentHashMap.newKeySet();
    @Override
    public void configureMessageBroker(MessageBrokerRegistry config) {
        // 啟用簡單的消息代理
        config.enableSimpleBroker("/operate", "/response");
        // 設置應用程序目標前綴
        config.setApplicationDestinationPrefixes("/app");
        // 設置用戶目標前綴
        config.setUserDestinationPrefix("/user");
    }

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        // 註冊STOMP端點，支持SockJS和原生WebSocket
        registry.addEndpoint("/kdlweb-websocket")
                .setAllowedOriginPatterns("*")
                .withSockJS();
        
        // 同時支持原生WebSocket
        registry.addEndpoint("/kdlweb-websocket")
                .setAllowedOriginPatterns("*");
    }


    @Override
    public void configureWebSocketTransport(WebSocketTransportRegistration registration) {
        registration.setMessageSizeLimit(MESSAGE_SIZE_LIMIT);
        registration.setSendTimeLimit(20000);
        registration.setSendBufferSizeLimit(512 * 1024);
    }

    @Override
    public void configureClientInboundChannel(ChannelRegistration registration) {
        registration.interceptors(new ChannelInterceptor() {
            @Override
            public Message<?> preSend(Message<?> message, MessageChannel channel) {
                StompHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class);
                if (accessor != null) {
                    StompCommand command = accessor.getCommand();
//                    logger.info("收到STOMP命令: {} -目标: {} - 会话: {}",
//                        command,
//                        accessor.getDestination(),
//                        accessor.getSessionId());
                    
                    // 詳細記錄STOMP幀信息
                    if (command == StompCommand.CONNECT) {
                        String sessionId = accessor.getSessionId();
                        if (sessionId != null && activeSessions.add(sessionId)) {
                            int count = connectionCount.incrementAndGet();
                            logger.info("WebSocket连接已建立，会话ID: {}, 当前连接数: {}", sessionId, count);
                        }

                        logger.info("STOMP连接请求 - 版本: {}, 心跳: {}",
                            accessor.getAcceptVersion(), 
                            accessor.getHeartbeat());
                    } else if (command == StompCommand.SEND) {
                        logger.info("STOMP发送消息 - 目标: {}, 内容类型: {}",
                            accessor.getDestination(), 
                            accessor.getContentType());
                    } else if (command == StompCommand.SUBSCRIBE) {
                        logger.info("STOMP订阅 - 目标: {}, 订阅ID: {}",
                            accessor.getDestination(), 
                            accessor.getSubscriptionId());
                    }
                }
                return message;
            }

            @Override
            public void afterSendCompletion(Message<?> message, MessageChannel channel, boolean sent, Exception ex) {
                // 处理连接断开情况
                StompHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class);
                if (accessor != null && accessor.getCommand() == StompCommand.DISCONNECT) {
                    String sessionId = accessor.getSessionId();
                    if (sessionId != null && activeSessions.remove(sessionId)) {
                        int count = connectionCount.decrementAndGet();
                        logger.info("WebSocket连接已断开，会话ID: {}, 当前连接数: {}", sessionId, count);
                    }
                }

                if (ex != null) {
                    logger.error("STOMP消息发送失败", ex);
                }
            }
        });
    }
}
